/*
 * jQuery functions for GRAND Flash Media
 */ 

var play_with_page = false;

jQuery(document).ready(function(){

/* MediaLibActions */
	msg_selected(true);

	jQuery('#gm-message').click(function(event){
		if(jQuery(event.target).hasClass('gm-close'))
			jQuery('.gm-message', this).fadeOut(200);
	});

	jQuery('.msg').click(function(){
		jQuery('.actions',this).toggle()
	}).bind('clickoutside',function(){
		jQuery('.actions',this).hide();
	});

	jQuery('.dropbut').click(function(){
		jQuery(this).parent().toggleClass('active');
	}).bind('clickoutside',function(){
		jQuery(this).parent().removeClass('active');
	});

	jQuery('#clearSelected').click(function(){
		jQuery('#selected_items').val('');
		chk_none('');
		msg_selected(true);
	});

	jQuery('#showSelected').click(function(){
		jQuery('#selectedForm').submit();
	});

	jQuery('.gMediaLibActions .doaction:checkbox').click(function(e) {
		var tr = ':visible';
		jQuery(this).parent().parent().removeClass('active');
		if(jQuery(this).is(':checked')){
			chk_all(tr);
		} else {
			chk_none(tr);
		};
		msg_selected();
		jQuery('body').trigger('click');
		e.stopPropagation();
	});
	jQuery('.gMediaLibActions .cb .dropbox').click(function(e) {
		var sel = jQuery(e.target).attr('class');
		var tr = '';
		switch(sel){
			case 'all':
				chk_all(tr);
			break;
			case 'none':
				chk_none(tr);
			break;
			case 'reverse':
				chk_toggle();
			break;
			case 'image':
			case 'audio':
			case 'video':
				tr = '.'+sel;
				chk_all(tr);
			break;
		}
		msg_selected();
	});
	jQuery('#gMediaLibTable td.cb :checkbox').click(function(){
		var arr = jQuery('#selected_items').val();
		var cur = jQuery(this).val();
		if(jQuery(this).is(':checked')){
			if(arr) { arr = arr+','+cur; } else { arr = cur; }
		} else {
			arr = jQuery.grep(arr.split(','), function(a){ return a != cur; }).join(',');
		};
		jQuery('#selected_items').val(arr);
		msg_selected(true);
	});

	/*jQuery('.abuts a').click(function(){
		var type = jQuery(this).attr('rel');
		var qty = jQuery('.page',this).text();
		//if(qty != 0) {
			if(type == 'all')
				jQuery('.gMediaLibTable tbody:visible tr').not('tr.noitems').show();
			else {
				jQuery('.gMediaLibTable tbody:visible tr').hide();
				jQuery('.gMediaLibTable tbody:visible tr.'+type).show();
			}
			jQuery(this).addClass('active').siblings().removeClass('active');
			msg_selected();
		//}
		//return false;
	});*/

	var grandSearch = jQuery('input[type="search"]');
	if(grandSearch && play_with_page) {
		grandSearch.quicksearch('table.gMediaLibTable tbody tr', {
				'delay': 100,
				'loader': 'span.loading',
				'bind': 'keypress', 
				'noResults': 'tr.noitems',
				'onBind': function (inp) {
						msg_selected();
						typedisplay();
					}
		}); 
	}

	// here we declare the parameters to send along with the request
	// this means the following action hooks will be fired:
	// wp_ajax_nopriv_myajax-submit and wp_ajax_myajax-submit
	// action : data.action,
	// 'cookie' which contains the cookie required to authenticate you admin access to admin-ajax.php
	// 'cookie' : encodeURIComponent(document.cookie),
	// other parameters can be added along with "action"
	// _ajax_nonce : data._ajax_nonce,
	// data : postdata
	jQuery('.ajax-post').click(function(event){
		var edata = jQuery(this).dataset();
		if(edata.form) {
			var form = edata.form;
			edata.form = jQuery('#'+edata.form).serialize().replace(/%5B%5D/g, '[]');
			if(!edata.form) {
				alert(0);
				return false;
			}
		}
		jQuery.ajax({
            type: "POST",
			url: ajaxurl,
			data: edata,
		   	cache: false,
		   	timeout: 10000,
		   	success: function(msg){
               	gmMessage(msg.stat, msg.message);
				switch(edata.action) {
					case 'gmedia_hidden':
						if(msg.stat == 'OK') {
							var sel = jQuery('#'+form+' table.gMediaLibTable tbody:visible td.cb input:checked').removeAttr('checked').parent().parent().parent();
							var tr = sel.detach();
							msg_selected();
							countmedias();
						}
					break;
					case 'gmSaveWPmedia':
						var row = jQuery(event.target).parents('tr:first');
						if(msg.stat == 'OK'){
							row.prev().replaceWith(msg.content);
							row.remove();
						} else if(msg.stat == 'KO') {
							row.prev().show();
							row.remove();
						}
					break;
				}
		    },
		    error: function (msg) {
               	gmMessage(msg.stat, msg.message);
			},
            complete: function () {
            }
		});
	});

	jQuery('.grandmedia').delegate('[toolTip]', 'mouseover', function(event) {
	  if(toolTip = jQuery(this).attr('toolTip')) {
		jQuery(this).qtip({
      		overwrite: false,
			content: {
				text: function(api) {
					return toolTip;
				}
			},
			position: {
			   my: 'left bottom',
			   at: 'top right'
			},
			show: {
			   solo: true,
			   event: event.type,
			   ready: true
			},
			hide: {
			   delay: 100,
			   fixed: true
			}
		}, event);
	  }
	});

	jQuery('.gMediaLibTable td.file img').qtip({
		content: {
			text: function(api) {
				var txt = '<img src="'+jQuery(this).attr('src')+'" width="150" style="height:auto;" alt="'+jQuery(this).attr('alt')+'" />';
				return txt;
			},
			title: function(api) {
				var tit = '<div class="title">'+jQuery(this).attr('title')+'</div>';
				return tit;
			}
		},
		position: {
		   my: 'left top',
		   at: 'top right',
		   container: jQuery('div.tooltip-file-preview'),
		   viewport: jQuery('.gMediaLibTable'),
		   adjust: {
		      x: 10, y: -2,
		      method: 'shift',
		      resize: false
		   },
		},
		show: {
		   delay: 300,
		   solo: jQuery('div.tooltip-file-preview')
		},
		hide: {
		   delay: 500,
		   fixed: true
		},
		style: {
		   classes: 'ui-tooltip-jtools no-close-button ui-tooltip-preview',
		   tip: {
		      corner: false
		   }
		},
	});

	jQuery('a.fancy-listen, a.fancy-watch').each(function(){
		// We make use of the .each() loop to gain access to each element via the "this" keyword...
		jQuery(this).qtip({
	    	content: {
	        	text: false,
				title: false,
	        	ajax: {
	        		url: jQuery(this).attr('href'), // Use the rel attribute of each element for the url to load
					once: true
	        	}
			},
			position: {
				at: 'left center', // Position the tooltip above the link
				my: 'right center',
				container: jQuery('div.tooltip-flash'),
		   		viewport: jQuery(window),
			},
			show: {
				event: 'click',
				solo: jQuery('div.tooltip-flash') // Only show one tooltip at a time
			},
			hide: 'unfocus',
			style: {
				classes: jQuery(this).attr('class')
			}
		});
	})
	// Make sure it doesn't follow the link when we click it
	.click(function(event) { event.preventDefault(); });

	jQuery('.confirm').click(function(){
		return confirm(jQuery(this).dataset('txt'));
	});
	
	jQuery('.fancy-view').fancybox({
		'titleFormat'	: function(title, currentArray, currentIndex, currentOpts) {
			title = jQuery(currentArray[currentIndex]).parents('tr:first').find("td.title span").text();
			return (title.length? '<table cellspacing="0" cellpadding="0" id="fancybox-title-float-wrap"><tbody><tr><td id="fancybox-title-float-left"></td><td id="fancybox-title-float-main">'+title+'</td><td id="fancybox-title-float-right"></td></tr></tbody></table>' : '');
		}
	});
	/*jQuery('.fancy-watch').fancybox({
		'type'	: 'iframe',
		'padding' : 0,
		'width' : 520,
		'height': 304,
		//'showNavArrows' : false,
		'titleFormat'	: function(title, currentArray, currentIndex, currentOpts) {
			title = jQuery(currentArray[currentIndex]).parents('tr:first').find("td.title span").text();
			return (title.length? '<table cellspacing="0" cellpadding="0" id="fancybox-title-float-wrap"><tbody><tr><td id="fancybox-title-float-left"></td><td id="fancybox-title-float-main">'+title+'</td><td id="fancybox-title-float-right"></td></tr></tbody></table>' : '');
		}
	});*/

	jQuery('.actions .edit').live('click', function(event){
		var EditRow = jQuery(this).parents('tr:first');
		var ID = parseInt( EditRow.find('.id span').text(), 10 );
		var InlineForm = jQuery('#gmedia-edit-inline .gmedia-edit-row').clone(true);
		InlineForm.find('fieldset').attr('id', function(i, val) { return val + ID });
		InlineForm.find('.legendID').text(ID);
		InlineForm.find('input[name="gmID"]').val(ID);
		InlineForm.find('.gmImage img').attr('src', EditRow.find('.file img').attr('src'));
		InlineForm.find('.gmImage .gmImageEdit').attr('href', function(i, val) { return val + ID });
		InlineForm.find('.gmFile .value').text(EditRow.find('.file .grandbox').attr('href').split('/').pop());
		InlineForm.find('.gmTitle input').val(EditRow.find('.title span').text());
		InlineForm.find('.gmDescription textarea').val(EditRow.find('.descr > div').html());
		InlineForm.find('.save').attr('data-form', function(i, val) { return val + ID });
		EditRow.hide().after(InlineForm);
		event.preventDefault();
	})
	jQuery('.gmedia-edit-row .buttons .button').click(function(event){
		if(jQuery(this).hasClass('cancel')){
			var EditRow = jQuery(this).parents('tr:first');
			EditRow.prev().show();
			EditRow.remove();
		}
		event.preventDefault();
	})

});
/*		// Define configuration defaults
		prerender: false,
		id: false,
		overwrite: true,
		metadata: {
		   type: 'class'
		},
		content: {
		   text: true,
		   attr: 'title',
		   title: {
		      text: false,
		      button: false
		   }
		},
		position: {
		   my: 'top left',
		   at: 'bottom right',
		   target: false,
		   container: false,
		   viewport: false,
		   adjust: {
		      x: 0, y: 0,
		      mouse: true,
		      method: 'flip',
		      resize: true
		   },
		   effect: true
		},
		show: {
		   target: false,
		   event: 'mouseenter',
		   effect: true,
		   delay: 90,
		   solo: false,
		   ready: false,
		   modal: {
		      on: false,
		      effect: true,
		      blur: true,
		      keyboard: true
		   }
		},
		hide: {
		   target: false,
		   event: 'mouseleave',
		   effect: true,
		   delay: 0,
		   fixed: false,
		   inactive: false,
		   leave: 'window',
		   distance: false
		},
		style: {
		   classes: '',
		   widget: false,
		   tip: {
		      corner: true,
		      mimic: false,
		      method: true,
		      width: 9,
		      height: 9,
		      border: 0,
		      offset: 0
		   }
		},
		events: {
		   render: null,
		   move: null,
		   show: null,
		   hide: null,
		   toggle: null,
		   focus: null,
		   blur: null
		}
*/
function msg_selected(single){
	//var qty = jQuery('table.gMediaLibTable tbody:visible td.cb input').length;
	var sel = jQuery('table.gMediaLibTable td.cb input:checked').length;
	var qty_v = jQuery('table.gMediaLibTable tr:visible td.cb input').length;
	var sel_v = jQuery('table.gMediaLibTable tr:visible td.cb input:checked').length;
	var c = jQuery('.gMediaLibActions .cb .dropbut :checkbox');
	if(sel_v!=qty_v && sel_v!=0){ c.css('opacity','0.5').attr('checked',true); }
	else if(sel_v==qty_v && qty_v!=0){ c.css('opacity','1').attr('checked',true); }
	else if(sel_v==0){ c.css('opacity','1').removeAttr('checked'); }

	var arr = jQuery('#selected_items').val().split(',');
	arr = jQuery.grep(arr, function(e){ return(e); });
	if(!single) {
		var cur = false;
		jQuery("table.gMediaLibTable td.cb input").each(function() {
			cur = jQuery(this);
			if(cur.is(':checked') && (jQuery.inArray(cur.val(), arr) === -1)) {
		    	arr.push(cur.val());
			} else if(jQuery.inArray(cur.val(), arr) !== -1) {
		    	arr = jQuery.grep(arr, function(e) { return e != cur.val(); });
			}
		});
		jQuery('#selected_items').val(arr.join(','));
	}
	var storedData = getStorage('gmedia_');
	storedData.set('selected_items', arr);
	var msg = jQuery('.gMediaLibActions .msg .selectedItems').text( arr.length ).parent();
	if(arr.length)
		msg.addClass('showmore').children('.more').attr('toolTip', '#' + arr.join(', #')).qtip('enable');
	else {
		msg.removeClass('showmore').children('.more').removeAttr('toolTip').qtip('disable');
	}
}
function getStorage(key_prefix) {
    // this function will return us an object with a "set" and "get" method
    // using either localStorage if available, or defaulting to document.cookie
    /*if (window.localStorage) {
        // use localStorage:
        return {
            set: function(id, data) {
                localStorage.setItem(key_prefix+id, data);
            },
            get: function(id) {
                return localStorage.getItem(key_prefix+id);
            }
        };
    } else {*/
        // use document.cookie:
        return {
            set: function(id, data) {
                document.cookie = key_prefix+id+'='+encodeURIComponent(data);
            },
            get: function(id, data) {
                var cookies = document.cookie, parsed = {};
                cookies.replace(/([^=]+)=([^;]*);?\s*/g, function(whole, key, value) {
                    parsed[key] = unescape(value);
                });
                return parsed[key_prefix+id];
            }
        };
    //}
}

function chk_all(tr){
	jQuery('table.gMediaLibTable tbody:visible tr'+tr+' td.cb :checkbox').attr('checked',true);
}
function chk_none(tr){
	jQuery('table.gMediaLibTable tr'+tr+' td.cb :checkbox').removeAttr('checked');
}
function chk_toggle(){
	jQuery('table.gMediaLibTable tbody:visible tr:visible td.cb :checkbox').each(function(){this.checked = !this.checked});
}
function typedisplay(){
	var hid = jQuery('table.gMediaLibTable tbody:visible tr:hidden').not('.noitems').length;
	if(hid){
		jQuery('.gMediaLibActions .abuts a').removeClass('active');
	} else {
		jQuery('.gMediaLibActions .abuts a').removeClass('active');
		jQuery('.gMediaLibActions .abuts a.all').addClass('active');
	}
}
function countmedias(){
	var i = jQuery('table.gMediaLibTable tbody:visible tr.image').length;
	var a = jQuery('table.gMediaLibTable tbody:visible tr.audio').length;
	var v = jQuery('table.gMediaLibTable tbody:visible tr.video').length;
	var o = jQuery('table.gMediaLibTable tbody:visible tr.other').length;
	jQuery('.gMediaLibActions .abuts').each(function(){
		jQuery('.all .page',this).text(i+a+v+o);
		jQuery('.image .page',this).text(i);
		jQuery('.audio .page',this).text(a);
		jQuery('.video .page',this).text(v);
		jQuery('.other .page',this).text(o);
	});
}
function gmMessage(stat, message){
	//jQuery.post(ajaxurl, { action: 'gmMessage', stat: stat, message: message }, function(response){ jQuery('#gm-message').html(response); });
	jQuery('#gm-message').html(message);
}
